<!-- 规范库 -->
<template lang="pug">
.home-wrap
    .tree-ww
        .btn-ww(v-if="query==1")
            el-button(type="primary" @click="upFile()" size="small" link) 上传文件
            el-button(type="primary" @click="standardLibraryUploadRef.open(choseNode,'批量上传')" size="small" link) 上传压缩包
            el-button(type="primary" @click="downloadAllWithDir(0)" size="small" link) 下载目录
            el-button(type="primary" @click="downloadAllWithDir(1)" size="small" link) 下载全部
        .tree-in
            treeModel(
                ref="eltreeRef"
                :data="treeData"
                :defaultProps="{ id: 'id', children: 'children', label: 'nodeName', parentId: 'parentId' }"
                @node-click="handleNodeClick"
                :emptyText="emptyText"
                :default-expand-all="true"
                :toolLight="true"
                @append="append"
                @edit="edits"
                @remove="cyDirdeleteById"
                :removeBefore="true"
            )
    .view-wrap
        .search-w
            searchModel(:searchList="searchList" @searchSubmit="searchSubmit" @searchReset="searchReset()")
                template(#searchSlot)
                    el-button(type="primary" @click="cyFiledownloadById()" style="margin-left: 22px" v-if="query==1") 批量下载
                    el-button(type="primary" @click="cyFiledeleteById()" v-if="query==1") 批量删除
        .table-w
            tableModel(
                ref="tableRef"
                :data="showData"
                :page="page"
                @pageChage="pageChage"
                :selection="query==1"
                @selection-change="selectChange"
            )
                el-table-column(prop="fileName" label="文件名称" align="center" show-overflow-tooltip)
                    //- template(#default="{row}")
                    //-     el-button(link type="primary" size="small" @click.stop="showFile(row)") {{ row.fileName }}
                el-table-column(prop="versionNum" label="版本号" align="center"  width="100" show-overflow-tooltip v-if="query==1")
                    template(#default="{row}")
                        span V{{ row.versionNum }}
                el-table-column(prop="fileStatus" label="文件状态" align="center" width="100" show-overflow-tooltip v-if="query==1")
                    template(#default="{row}")
                        span(:style="{color: row.fileStatus == 1 ? '' : 'red'}") {{ row.fileStatus == 1 ? '正常使用' : '作废' }}
                el-table-column(prop="parseStatus" label="解析状态" align="center" width="100" show-overflow-tooltip v-if="query==1")
                    template(#default="{row}")
                        span(style="color:red" v-if='row.parseStatus == 0') 解析失败
                        span(v-else) {{ row.parseStatus == 1 ? '解析中' : '解析完成' }}
                el-table-column(prop="createDate" label="上传时间" align="center"  width="180" show-overflow-tooltip v-if="query==1")
                el-table-column(label="操作" align="center" width="210px")
                    template(#default="{row}")
                        el-button(link type="primary" size="small" @click.stop="showFile(row)"  ) 预览
                        el-button(link type="primary" size="small" @click.stop="cyFilesaveOne(row,'作废')"  v-if="query==1") {{row.fileStatus == 1?'作废':'取消作废'}}
                        el-button(link type="primary" size="small" @click.stop="cyFiledownloadById(row)"  ) 下载
                        el-button(link type="primary" size="small" @click.stop="cyFiledeleteById(row)"  v-if="query==1") 删除
                el-table-column(label="收藏" align="center" width="60")
                    template(#default="{row}" )
                        el-icon(size="16" style="cursor: pointer;" @click="cyFilesaveOne(row,'收藏')")
                            StarFilled( :title="row.collectStatus == 1 ? '以收藏' : '收藏'" :style="{color:row.collectStatus == 1 ? '#fa9734' : '#ccc'}" )
standardLibraryAdd(ref="standardLibraryAddRef" @createSuccess="cyDirqueryAll()")
standardLibraryUpload(ref="standardLibraryUploadRef" @updateSuccess="updateSuccess")
fileView(ref="fileViewRef")
</template>

<script setup>

import searchModel from '@/components/searchModel.vue'
import treeModel from '@/components/treeModel.vue'
import tableModel from '@/components/tableModel.vue'
import { ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { storageGet, storageClear, storageSet } from '@/utils'
import apis from '@/apis'
import { success, warning, deleteConfirm } from '@/utils/message'
import { muenStore } from '@/stores'
import standardLibraryAdd from './component/standardLibraryAdd.vue'//编辑
import standardLibraryUpload from './component/standardLibraryUpload.vue'//上次
import fileView from '@/components/fileView.vue'//预览


const router = useRouter()
const route = useRoute()

//上传成功
const updateSuccess = (type) => {
    cyFilequeryAllSplit()
    if(type == 'zip'){
        cyDirqueryAll()
        cyFilequeryAllSplit()
    }
}

const query = ref('')//0预览，1入库
watch(()=>route.query, ()=>{
    query.value = route.query.type
    cyDirqueryAll()
    cyFilequeryAllSplit()
    window.Favorites = cyFilequeryAllSplit
})
const standardLibraryAddRef = ref()
const append = (data) => {
    standardLibraryAddRef.value.open(data, '新增')
}
const edits = (data) => {
    standardLibraryAddRef.value.open(data, '编辑')
}
//预览
const fileViewRef = ref()
const showFile = (data) => {
    fileViewRef.value.open(data)
}

const cyDirdeleteById = (data) => {//删除
    deleteConfirm(() => {
        apis.cyDirdeleteById({
            id: data.id
        }).then(res => {
            if(res.status == 1){
                success(res.msg)
                cyDirqueryAll()
            }else{
                warning(res.msg)
            }
        })
    })
}
//获取树
const eltreeRef = ref()
const treeData = ref([])
const emptyText = ref('加载中')
const treeType = ref('')
const cyDirqueryAll = () => {
    treeType.value = ''
    treeData.value = []
    apis.cyDirqueryAll({ }).then(res => {
        emptyText.value = '暂无数据'
        choseNode = {}

        function run(arr){
            arr.forEach(val => {
                if(query.value == 1){
                    val.addShow = true
                    val.editShow = true
                    val.delShow = true
                    if(val.parentId == '-1'){
                        val.delShow = false
                    }
                }

                val.isfolder = true//文件夹图标
                if(val.children && val.children.length){
                    run(val.children)
                }
            })
        }
        run(res.data)
        treeData.value = res.data
        if(!choseNode.id){
            res.data.forEach(val => {
                if(val.parentId == '-1'){
                    choseNode = val
                }
            })
        }
        setTimeout(()=>{
            eltreeRef.value.setCurrentKey(choseNode.id)
        }, 300)
    })
}
//目录下载，全部下载
const downloadAllWithDir = (type)=>{
    apis.downloadAllWithDir({
        includeFile: type//1-是 0-否
    })
}
//选中节点
const handleNodeClick = (data) => {
    choseNode = data
    cyFilequeryAllSplit()
}

let choseNode = {}


//复选
let checks = []
const selectChange = (val) => {
    checks = val
}

//文件列表
const searchList = [
    { type: 'input', label: '文件名称', maxlength: 50, prop: 'fileName' }
]

const data = ref([])

//上传
const standardLibraryUploadRef = ref()
const upFile = () => {
    if(!choseNode.id){
        warning('请选择目录')
        return
    }
    standardLibraryUploadRef.value.open(choseNode)
}
let results = {}
const searchSubmit = result => {
    results = result
    cyFilequeryAllSplit()
}
const searchReset = () => {
    results = {}
    cyFilequeryAllSplit()
}
//列表
const tableData = ref([])
const cyFilequeryAllSplit = () => {
    page.value.currentPage = 1
    apis.cyFilequeryAllSplit({
        ...results,
        dirId: choseNode.id,
        fileStatus: query.value == 1 ? '' : '1', //1-正常使用 0-作废
        collectStatus: ''//1-已收藏 0-未收藏
    }).then(res => {
        if(res.status == 1){
            tableData.value = res.data
            page.value.total = res.data.length
            showInit()
        }
    })
}
const page = ref({
    total: 0,
    pageSize: 20,
    currentPage: 1
})
const tableRef = ref()
const pageChage = () => {
    checks = []
    tableRef.value.clearSelection()
    showInit()
}
//列表根据分页显示
const showData = ref([])
const showInit = () => {//前端分页
    showData.value = tableData.value.slice((page.value.currentPage - 1) * page.value.pageSize, (page.value.currentPage - 1) * page.value.pageSize + page.value.pageSize)
}
//批量删除-文件
const cyFiledeleteById = (row) => {
    let ids = ''
    if(row){
        ids = row.id
    }else{
        if(checks.length == 0){
            warning('请选择要删除的文件')
            return
        }
        ids = checks.map(val => val.id).join(',')
    }

    deleteConfirm(() => {
        apis.cyFiledeleteById({
            idList: ids
        }).then(res => {
            if(res.status == 1){
                success(res.msg)
                cyFilequeryAllSplit()
            }else{
                warning(res.msg)
            }
        })
    })

}
//下载
const cyFiledownloadById = (row) => {
    if(row){
        apis.cyFiledownloadById({
            id: row.id,
            type: 1
        })
    }else{
        if(checks.length == 0){
            warning('请选择要删除的文件')
            return
        }

        let ids = checks.map(val => val.id).join(',')
        apis.cyFiledownloadByIds({
            idList: ids
        })
    }
}
//修改（收藏，作废）
const cyFilesaveOne = (row, type) => {
    let obj = {}
    if(type == '收藏'){
        obj.collectStatus = row.collectStatus == 1 ? 0 : 1
    }else{//作废
        obj.fileStatus = row.fileStatus == 1 ? 0 : 1
    }
    apis.cyFilesaveOne({
        id: row.id,
        ...obj
    }).then(res => {
        if(res.status == 1){
            success(res.msg)
            cyFilequeryAllSplit()
        }else{
            warning(res.msg)
        }
    })
}
onMounted(()=>{
    query.value = route.query.type
    // cyDirqueryAll()
    // cyFilequeryAllSplit()
    window.Favorites = cyFilequeryAllSplit
})

const add = () => {

}
</script>
<style lang="less" scoped>
.home-wrap{
    width: 100%;
    height: 100%;
    display: flex;
    overflow: hidden;
    padding: 0 20px;
    .tree-ww{
        height: 100%;
        border-right: 1px solid #ccc;
        box-shadow: 0 0 10px #eee;
        width: 320px;
        display: flex;
        flex-direction: column;
        .btn-ww{
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-around;
            padding: 0 10px;
            border-bottom: 1px solid #ccc;
            box-shadow: 0 0 10px #eee;
        }
        .tree-in{
            flex-grow: 1;
            overflow: hidden;
        }
    }
    .view-wrap{
        flex: 1;
        height: 100%;
        display: flex;
        overflow: hidden;
        flex-direction: column;
        .tool-w{
            display: flex;
            align-items: center;
            justify-content: flex-end;
            padding: 0 20px;
        }
        .table-w{
            flex-grow: 1;
            overflow: hidden;
        }
    }
    :deep(.el-button){
        span {
            white-space: break-spaces;
        }
    }
}
</style>